package com.appbee.media.server;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.channels.Channels;
import java.util.logging.Logger;

import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

@Singleton
public class ThumbnailService extends HttpServlet
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(ThumbnailService.class.getName());
	
	private Provider<MediaDAO> photoDaoProvider;
	private BlobstoreService blobstoreService;

	
	@Inject
	public ThumbnailService(Provider<MediaDAO> photoDaoProvider,BlobstoreService blobstoreService)
	{
		super();
		this.photoDaoProvider = photoDaoProvider;
		this.blobstoreService = blobstoreService;
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		log.info("service photo id: "+req.getParameter("id"));
		Media photo = photoDaoProvider.get().findById(Long.parseLong(req.getParameter("id")));
		if(photo==null) return;
		
		if(photo.getThumbnailBlobKey()==null)
		{
			saveThumbnail(photo);
		}
		
		BlobKey blobKey = new BlobKey(photo.getThumbnailBlobKey());
        blobstoreService.serve(blobKey, resp);
        
	}
	
	private void saveThumbnail(Media photo) throws IOException
	{
		ImagesService imagesService = ImagesServiceFactory.getImagesService();

        Image oldImage = ImagesServiceFactory.makeImageFromBlob(new BlobKey(photo.getStrId()));
        Transform resize = ImagesServiceFactory.makeResize(300, 200);

        Image newImage = imagesService.applyTransform(resize, oldImage);

		// Get a file service
		  FileService fileService = FileServiceFactory.getFileService();

		  // Create a new Blob file with mime-type "text/plain"
		  AppEngineFile file = fileService.createNewBlobFile("image/jpeg");

		  // Open a channel to write to it
		  boolean lock = true;
		  FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);

		  // are possible. Here we use a Outputstream:
		  BufferedOutputStream out = new BufferedOutputStream(Channels.newOutputStream(writeChannel));
		  out.write(newImage.getImageData());

		  // Close without finalizing and save the file path for writing later
		  out.close();
		  
		 
		  // Now finalize
		  writeChannel.closeFinally();
		  
		  BlobKey blobKey = fileService.getBlobKey(file);
		  photo.setThumbnailBlobKey(blobKey.getKeyString());
		  photoDaoProvider.get().update(photo);
		  
	}

}
